onload = () => {
    loadCSS("../css/common.css", "common");
    loadCSS("../css/clientrate.css", "page");
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadScript("../js/bootstrap5.bundle.min.js")
        .then(() => loadScript("../addon/autocomplete/autocomplete.js")).then(() => loadScript("../js/crud.js")).then(() => {
        let clientRateOperator = new Crud({
            module: "clientRate",
            hasCheckbox: true,
            extraInformation: [{caption: "Charge Code", field: "clientRateId_clientRateCharge.chargeCode"}],
            extendAttribute: [{name: "clientRateId", type: "clientRateCharge"}],
            rowEvent: function (e, item, tr, outer) {
                outer.subTable["clientRateCharge"].load(item["clientRateId_clientRateCharge"]);
                canvas.show();
            },
            inputQueryOpt: {
                "client.name": {
                    mapper: {"clientName": "name", "clientId": "clientId"},
                    match: value =>
                        ajaxAsync("/client/list", {
                            body: {
                                "pageSize": -1,
                                "data": {
                                    "name": value
                                }
                            }, method: "POST"
                        }),
                    renderCell: data => {
                        const li = document.createElement("li");
                        li.classList.add("dropdown-item");
                        li.textContent = data.name;
                        return li;
                    }
                }, "jobtype.name": {
                    mapper: {"jobTypeName": "name", "jobTypeId": "jobTypeId"},
                    match: value =>
                        ajaxAsync("/job_type/list", {
                            body: {
                                "pageSize": -1,
                                "data": {
                                    "name": value
                                }
                            }, method: "POST"
                        }),
                    renderCell: data => {
                        const li = document.createElement("li");
                        li.classList.add("dropdown-item");
                        li.textContent = data.name;
                        return li;
                    }
                }
            },
            iterators: [{
                name: "client.rate.type",
                iterator: [{"value": 0, "caption": "Transport"}, {"value": 1, "caption": "Truck"}]
            }],
            rowBtn: ["edit", "delete",{
                "caption": "icon-icon-upload-cloud",
                hint: "Upload to CW",
                "class": "btn-warning", "callback": e => {
                    e.stopPropagation();
                    const id = parseInt(e.target.closest("button").getAttribute("data-id"));
                    ajax(`/rate/export?clientRateId=${id}`, {}, (data) => showToast(`message: ${data.message}<br/> Response: ${JSON.stringify(data)}`, data.data && "primary"), (error) =>
                        showToast(error))
                }
            }],
            opsButton: ["new", {
                "caption": "Upload Quote File(xslx)",
                "class": "btn btn-primary",
                "action": "modal",
                "param": "#uploadQuoteFile",
                "commit": (form) => {
                        const fileInput = form.querySelector('#formFile');
                        const formData = new FormData();
                        formData.append('file', fileInput.files[0]);
                        return ajax("/rate/excel", {method: "POST", body: formData, headers: {}}, data => {
                            showToast(`Upload successful: ${JSON.stringify(data.data)}`);
                            let modalElement = document.getElementById("uploadQuoteFile");
                            const modal = bootstrap.Modal.getInstance(modalElement)
                                || new bootstrap.Modal(modalElement);
                            modal.hide();
                        }, error => showToast(error.message));
                }
            }, "delete"],
            search: [
                {"caption": "Category", "name": "category", class: "col-3"}
            ],
            listField: [{"caption": "ID", "field": "clientRateId"},
                {"caption": "Client", "field": "client_code"},
                {"caption": "Mode", "field": "mode"},
                {"caption": "From", "field": "from_organization"},
                {"caption": "To", "field": "to_organization"},
                {"caption": "Start Date", "field": "startDate"},
                {"caption": "End Date", "field": "endDate"}],
            editFields: [
                {caption: "Client Code", "name": "clientCode", "placeHolder": "", class: "col-3"},
                {"name": "mode", "placeHolder": "", class: "col-3"},
                {"name": "category", "placeHolder": "", class: "col-3"},
                {"name": "fromOrganization", "placeHolder": "", class: "col-3"},
                {"name": "fromAddress", "placeHolder": "", class: "col-3"},
                {"name": "fromPostcode", "placeHolder": "", class: "col-3"},
                {"name": "toOrganization", "placeHolder": "", class: "col-3"},
                {"name": "toAddress", "placeHolder": "", class: "col-3"},
                {"name": "toPostcode", "placeHolder": "", class: "col-3"},
                {"name": "startDate", type: "date", "placeHolder": "", class: "col-3"},
                {"name": "endDate", type: "date", "placeHolder": "", class: "col-3"},
            ],
            subTable: [{
                name: "clientRateCharge",
                tableId: "clientRateCharge",
                listField: [{"caption": "Charge Code", "field": "chargeCode"},
                    {"caption": "Description", "field": "description"}],
            }]
        });
        clientRateOperator.init();
        function loadData() {
            warehouseOrderOperator.loadData();
        }
        const canvas = new bootstrap.Offcanvas(document.getElementById('subtable'));

    }).catch((err) => console.error(err));
}
